<template>
	<view class="real-name-container">
		<view class="u-demo-block">
			<text class="u-demo-block__title">自定义上传样式</text>
			<view class="u-demo-block__content">
				<view class="u-page__upload-item">
					<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="6" multiple
						:maxCount="1" width="250" height="150">
						<image src="https://cdn.uviewui.com/uview/demo/upload/positive.png" mode="widthFix"
							style="width: 250px;height: 150px;"></image>
					</u-upload>
				</view>
			</view>
		</view>
		<u-button type="primary" text="确认上传" customStyle="margin-top: 50px" @click="submitUpload()"></u-button>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				stu:{
					studentId:5
				},
				fileList: [],
				localFiles: [], // 存储本地图片路径
				isUploading: false, // 上传状态
				uploadResult: '', // 上传结果提示
			}
		},
		onLoad() {},
		methods: {
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1);
				this.localFiles.splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				let lists = [].concat(event.file);

				// 清空之前选择的图片（因为maxCount=1）
				this.fileList = [];
				this.localFiles = [];

				lists.forEach(item => {
					// 保存到文件列表（显示缩略图，但标记为待上传）
					this.fileList.push({
						url: item.url,
						status: 'waiting',
						message: '待上传'
					});

					// 保存本地路径，用于后续上传
					this.localFiles.push(item.url);
				});

				this.uploadResult = ''; // 清除之前的结果提示

			},
			async submitUpload() {
				 if (this.localFiles.length === 0) {
				        uni.showToast({
				            title: '请先选择身份证照片',
				            icon: 'none'
				        });
				        return;
				    }
				
				    this.isUploading = true;
				    this.uploadResult = '';
				
				    try {
				        // 获取本地文件
				        const localUrl = this.localFiles[0];
				        
				        // 使用uni.uploadFile上传文件
				        const uploadTask = uni.uploadFile({
				            url: 'http://localhost:8001/student/studentRecIdNumber', 
				            filePath: localUrl,
				            name: 'file', 
				            formData: {
				                studentId: this.stu.studentId 
				            },
				            success: (res) => {
								
				                const response = JSON.parse(res.data);
				                console.log(response);
				                if (response.code === 200) { 
				
				                    // 更新文件状态
				                    this.fileList[0] = {
				                        ...this.fileList[0],
				                        status: 'success',
				                        message: '识别成功'
				                    };
				
				                    this.uploadResult = '识别成功';
				                    uni.showToast({
				                        title: '实名认证成功',
				                        icon: 'success'
				                    });
				
				
				                    // 延迟后跳转到个人信息页
				                    setTimeout(() => {
										// 触发页面刷新的事件
										    uni.$emit('refreshPersonInfo');
											
				                        uni.navigateTo({
				                            url: '/pages/person-info/person-info'
				                        });
				                    }, 1500);
				                } else {
									uni.showToast({
									    title: '实名认证失败',
									    icon: 'error'
									});
				                    
				                }
				            },
				            fail: (err) => {
				                console.error('上传失败:', err);
				                throw new Error('网络错误，请重试');
				            }
				        });
				        
				        
				        
				} catch (error) {
					console.error('实名认证失败:', error);
					this.uploadResult = error.message || '实名认证失败，请重试';

					// 更新文件状态
					if (this.fileList.length > 0) {
						this.fileList[0] = {
							...this.fileList[0],
							status: 'fail',
							message: '识别失败'
						};
					}
				} finally {
					this.isUploading = false;
				}
			},

		},
	}
</script>

<style lang="scss">
	.real-name-container {
		padding: 40rpx;
		background-color: #f8f8f8;
		min-height: 95vh;
		box-sizing: border-box;
		text-align: center;


	}

	.u-demo-block__content {
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>